import { useCallback, useEffect, useMemo, useState } from "react"
import type { FormItem } from "../../components/DynamicForm"
import { mockGetRoles, mockGetUserType, type UserRes, type Roles } from "../../utiles/mockData"
import { Tag } from "antd"
import type { ColumnPlusType } from "../../components/TablePlus/types"

export interface User {
  name: string
  email: string
  phone: string
  type: { name: string }
  roles: { id: string | number; name: string }[]
}


export const useSearchQuery = (): FormItem[] => {
  const [roles, setRoles] = useState<Roles>([])
  const [userTypes, setUserTypes] = useState<UserRes[]>([])

  useEffect(() => {
    mockGetRoles().then(res => { setRoles(res) })
    mockGetUserType().then(res => { setUserTypes(res) })
  }, [])

  const FormItems: FormItem[] = useMemo(() => {
    return [
      {
        label: '姓名',
        name: 'name',
        type: 'text',
        props: {
          placeholder: '请输入用户名',
        },
      },
      {
        label: '学工号',
        name: 'code',
        type: 'text',
        props: {
          placeholder: '请输入学工号',
        },
      },
      {
        label: '人员类型',
        name: 'userType',
        type: 'cascader',
        props: {
          options: userTypes,
          placeholder: '请选择人员类型',
          fieldNames: { value: 'value', label: 'label', children: 'children' },
        },
      },
      {
        label: '邮箱',
        name: 'email',
        type: 'text',
        props: {
          placeholder: '请输入邮箱',
        },
      },
      {
        label: '角色',
        name: 'role',
        type: 'select',
        props: {
          placeholder: '请选择邮箱',
          options: roles,
        },
      },
    ]
  }, [roles, userTypes])

  return FormItems
}


export function useUserColumns(
  onOperateClick?: (key: string, record: User) => void
): ColumnPlusType<User>[] {
  return [
    {
      dataIndex: 'name',
      title: '名称',
      key: 'name',
      width: 200
    },
    {
      dataIndex: 'email',
      title: '邮箱',
      key: 'email',
      align: 'center'
    },
    {
      dataIndex: 'phone',
      title: '联系方式',
      key: 'phone',
      align: 'center'
    },
    {
      dataIndex: 'type',
      title: '人员类型',
      key: 'type',
      render: (type) => type.name
    },
    {
      dataIndex: 'roles',
      title: '角色',
      key: 'roles',
      render: (roles) => (
        <div style={{ display: 'flex', flexWrap: 'wrap' }}>
          {roles.map((item: any) => (
            <Tag key={item.id} style={{ marginRight: 8 }}>{item.name}</Tag>
          ))}
        </div>
      )
    },
    {
      dataIndex: 'operation',
      title: '操作',
      key: 'operation',
      width: 200,
      fixed: 'right',
      operations: [
        {
          key: 'edit',
          label: '编辑',
          buttonProps: {
            style: {
              color: 'orange'
            }
          },
          show: (record) => {
            const isAdmin = record.roles.find((role: any) => role.name === '超级管理员');
            return !isAdmin;
          }
        },
      ],
      render: (_: any, record: User, index: number) => {
        return <>
          <a onClick={() => { alert('点击了查看') }}>查看</a>
        </>
      },
      operateClick: onOperateClick
        ? onOperateClick
        : (key: string, record: User) => {
          // console.log(key, record)
          alert(`点击了${key}按钮，当前行数据：${record.name}`)
        }
    }
  ]
}

export const mockGetData = async (params: Record<string, any>) => {
  const { page = 1, pageSize = 10, name = '' } = params;
  console.log("params>>", params);
  // 模拟延迟
  await new Promise(resolve => setTimeout(resolve, 500));

  // 创建模拟数据
  const mockUsers: User[] = Array.from({ length: 100 }, (_, index) => ({
    name: `用户${index + 1}${name ? `-${name}` : ''}`,
    email: `user${index + 1}@example.com`,
    phone: `1${Math.floor(Math.random() * 10000000000).toString().padStart(10, '0')}`,
    type: { name: index % 3 === 0 ? '管理员' : index % 3 === 1 ? '普通用户' : '访客' },
    roles: [
      { id: index, name: index % 4 === 0 ? '超级管理员' : index % 4 === 1 ? '编辑' : index % 4 === 2 ? '审核员' : '查看者' },
      ...(index % 3 === 0 ? [{ id: `extra-${index}`, name: '特殊角色' }] : [])
    ]
  }));

  // 模拟搜索过滤
  let filteredData = [...mockUsers];
  if (name) {
    filteredData = filteredData.filter(user =>
      user.name.includes(name) ||
      user.email.includes(name) ||
      user.phone.includes(name)
    );
  }

  // 分页处理
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedData = filteredData.slice(startIndex, endIndex);

  // 添加操作按钮
  const result = paginatedData.map(item => {
    return {
      ...item,
      actions: [
        { key: 'edit2', label: '接口返回' },
      ]
    };
  });

  // 返回模拟响应
  return {
    data: result as User[],
    total: filteredData.length,
    success: true
  };
};